
package com.gitee.hermer.boot.jee.commons.thread;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;


public class SyncFinisher {

	private CountDownLatch countDownLatch;

	private Set<Worker> workers = new LinkedHashSet<Worker>();

	/**
	 * 增加工作线程
	 * @param worker 工作线程
	 */
	synchronized public void addWorker(WorkInterface worker) {
		workers.add(new Worker(worker));
	}
	/**
	 * 开始工作
	 */
	public void start() {
		countDownLatch = new CountDownLatch(workers.size());
		for (Worker worker : workers) {
			worker.start();
		}
	}

	/**
	 * 等待所有Worker工作结束，否则阻塞
	 * @throws InterruptedException
	 */
	public void await() throws InterruptedException {
		if (countDownLatch == null) {
			throw new InterruptedException("Please call start() method first!");
		}

		countDownLatch.await();
	}

	/**
	 * 清空工作线程对象
	 */
	public void clearWorker() {
		workers.clear();
	}

	/**
	 * @return 并发数
	 */
	public long count() {
		return countDownLatch.getCount();
	}
	public interface WorkInterface{
		public void work();
	}
	
	public  class Worker extends Thread {
		WorkInterface inter;
		
		public Worker(WorkInterface inter){
			this.inter = inter;
		}
		
		
		@Override
		public void run() {
			try {
				inter.work();
			} finally {
				countDownLatch.countDown();
			}
		}
		
		

	}

}
